//
//	 ______    ______    ______    
//	/\  __ \  /\  ___\  /\  ___\   
//	\ \  __<  \ \  __\_ \ \  __\_ 
//	 \ \_____\ \ \_____\ \ \_____\ 
//	  \/_____/  \/_____/  \/_____/ 
//
//	Powered by BeeFramework
//
//
//  CartBoard.m
//  Pizza
//
//  Created by sendInfo on 2015-03-24.
//  Copyright (c) 2015年 sendInfo. All rights reserved.
//

#import "CartBoard.h"
#import "TopView.h"
#import "PullLoader.h"
#import "FootLoader.h"
#import "HomeBoard.h"
#import "OrderCell.h"
#pragma mark -

@implementation CartM
@end

@implementation CartFooterCell

SUPPORT_AUTOMATIC_LAYOUT(YES)
SUPPORT_RESOURCE_LOADING(YES)

- (void)load
{
    
    
}
- (void)dataDidChanged
{
    
    NSDictionary *dic = self.data;
    Order *om = dic[@"order"];
    NSString *time = dic[@"time"];
    
    $(@"money").DATA([NSString stringWithFormat:@"实付款:￥ %@",om.order_sumPrice]);
    
    if (time.length) {
        
        $(@"status").SHOW();
        $(@"money").SHOW();
    }else{
    
        $(@"status").HIDE();
        $(@"money").HIDE();
    }
    
    if ([om.status intValue]==1) {
        

        $(@"status").DATA(@"订单状态:未支付");
        
    }else if ([om.status intValue]==2){
    
        $(@"status").DATA(@"订单状态:待发货");
        
    }else if ([om.status intValue]==3){
        
        $(@"status").DATA(@"订单状态:待收货");
        
    }else if ([om.status intValue]==4){
        
        $(@"status").DATA(@"订单状态:完成");
        
    }else if ([om.status intValue]==5){
        
        $(@"status").DATA(@"订单状态:关闭");
    }
    
}


@end


@implementation SectionItemCell

SUPPORT_AUTOMATIC_LAYOUT(YES)
SUPPORT_RESOURCE_LOADING(YES)

- (void)load
{
    
    
}
- (void)dataDidChanged
{
    
    NSDictionary *dic = self.data;
    NSString *time = dic[@"time"];
    if (time.length == 0) {
        $(@"time").HIDE();
        $(@"title").HIDE();
        
    }else{
    
        $(@"time").SHOW();
        $(@"title").SHOW();
        $(@"time").DATA(dic[@"time"]);
    }
}

@end


@implementation addAddressCell

SUPPORT_AUTOMATIC_LAYOUT(YES)
SUPPORT_RESOURCE_LOADING(YES)

- (void)load
{
    
    
}
- (void)dataDidChanged
{
    
}

@end


@implementation SelectAddressItemCell

SUPPORT_AUTOMATIC_LAYOUT(YES)
SUPPORT_RESOURCE_LOADING(YES)

- (void)load
{
    
    
}
- (void)dataDidChanged
{
    
    Address *add = self.data;
    $(@"name").DATA(add.name);
    $(@"phone").DATA(add.mobile);
    $(@"address").DATA(add.address);
}

@end

@implementation SelectAddressCell

SUPPORT_AUTOMATIC_LAYOUT(YES)
SUPPORT_RESOURCE_LOADING(YES)

- (void)load
{
    
    
    self.list.lineCount = 1;
    self.list.animationDuration = 0.25f;
    self.list.whenReloading = ^{
    
        self.list.total = ((NSArray*)self.data).count;
        for (BeeUIScrollItem *item in self.list.items) {
            
            
            item.size = CGSizeMake(self.list.size.width, 90);
            item.clazz = [SelectAddressItemCell class];
            item.data = [((NSArray*)self.data) safeObjectAtIndex:item.index];
            
        }
    
    };
    
    NSDictionary *dic = @{@"token":[SendIFAPPDefault shareAppDefault].userToken,@"pageNumber":@"1",@"pageSize":@"1000"};
    self.MSG(HttpAPI.address).INPUT(@"body",dic);
    
}
- (void)dataDidChanged
{
    NSArray *arr = self.data;
    
    if (arr.count==0) {
        $(@"add").SHOW();
    }else{
    
        $(@"add").HIDE();
    }
    [self.list reloadData];
    
}

ON_MESSAGE3(HttpAPI, address, msg)
{

    if (msg.sending) {
        
        [self presentLoadingTips:@"地址获取中"];
        
    }else{
    
        [self dismissTips];
        if (msg.succeed)
        {
            NSArray *addressArr = msg.GET_OUTPUT(@"address");
            Status *sta = msg.GET_OUTPUT(@"status");
            
            if ([sta.code intValue]!=10000) {
            
                [self presentMessageTips:sta.message];
                return;
                
            }
            
            if (addressArr.count == 0) {
                
                [self presentMessageTips:@"没有地址，请添加地址"];
                
            }
            self.data = addressArr;
            
            
        }else if (msg.failed)
        {
        
            [self presentFailureTips:@"网络错误"];
            
        }
    }

}

@end



/*==========================================================================================*/
@implementation CartItemCell

SUPPORT_AUTOMATIC_LAYOUT(YES)
SUPPORT_RESOURCE_LOADING(YES)

- (void)load
{


}
- (void)dataDidChanged
{

    CartM *cm = self.data;
    Goods *gm = cm.goods;

    $(@"name").DATA(gm.title);
    $(@"introlab").DATA([NSString stringWithFormat:@"配料:%@",gm.burdening]);
    $(@"photo").DATA([NSString stringWithFormat:@"%@/%@",[HttpRequest sharedInstance].imageUrl,gm.pic]);
    //float price = [cm.goodsNum integerValue]*[gm.price floatValue];
    $(@"price").DATA([NSString stringWithFormat:@"%@ 元",gm.price]);
    $(@"numvalue").DATA([NSString stringWithFormat:@"%d",[cm.goodsNum intValue]]);
}

@end


/*==========================================================================================*/
@interface CartBoard()
{
	//
    UIImageView *_line;
    BeeUIButton *_lastBtn;
    UIView *bottomV;
    UITableView *_table;
    
    SelectAddressItemCell *_lastAddressCell;
    
    UILabel *numLab;
    int _allGoodsNum;
    UILabel *priceLab;
    
    NSString *_seleGids;
    NSString *_orderId;
    NSMutableArray *_noZeroArr;

}
@property(nonatomic,strong)BeeUIScrollView *list;
@property(nonatomic,assign)int currentIndex;
@property(nonatomic,strong)NSArray *historyData;
@end

@implementation CartBoard

SUPPORT_AUTOMATIC_LAYOUT( YES )
SUPPORT_RESOURCE_LOADING( YES )
DEF_MODEL(OrderM, ordm)
- (void)load
{
    
    NSDictionary *selectsD = [[NSUserDefaults standardUserDefaults] objectForKey:@"cart.selectgoods"];
    
    NSArray *before = [selectsD allValues];
    NSSortDescriptor *des = [[NSSortDescriptor alloc] initWithKey:@"gid" ascending:YES];
    NSArray *after = [before sortedArrayUsingDescriptors:[NSArray arrayWithObject:des]];
    
    NSArray *goods = [CartM objectsFromArray:after];
    
    _historyData = @[@{@"goods":goods==nil?[NSArray new]:goods}];
    
    self.currentIndex = 100;
    self.ordm = [OrderM modelWithObserver:self];
    self.ordm.orderType = @"current";
    
}

- (void)unload
{
    self.ordm = nil;
    
}
ON_DID_APPEAR(signal)
{

}
ON_CREATE_VIEWS(signal)
{
    self.navigationBarShown = NO;
    
    [self.back addTarget:self.navigationController.parentViewController action:@selector(revealToggle:) forControlEvents:UIControlEventTouchUpInside];
    
    UIImageView *bgimg = [[UIImageView alloc] initWithFrame:self.bounds];
    bgimg.image = [UIImage imageNamed:@"home-bg"];
    [self.view addSubview:bgimg];
    [self.view sendSubviewToBack:bgimg];
    

    
    NSArray *tits = @[@"购物车",@"当前订单",@"历史订单"];
    for (int i = 0; i<tits.count; i++) {
        
        BeeUIButton *headBtn =[[BeeUIButton alloc] initWithFrame:CGRectMake(i*self.size.width/3, 64, self.size.width/3, 30)];
        [headBtn setTitle:tits[i]];
        [headBtn addTarget:self action:@selector(headBtnClick:) forControlEvents:UIControlEventTouchUpInside];
        headBtn.tag = i+100;
        [headBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        headBtn.titleLabel.font = [UIFont systemFontOfSize:14];
        
        if (i == 0) {
            
            [headBtn setTitleColor:[UIColor colorWithString:@"#ed8929"] forState:UIControlStateNormal];
            
            _line = [[UIImageView alloc] initWithFrame:CGRectMake(10, CGRectGetMaxY(headBtn.frame)-3, headBtn.size.width-20, 3)];
            _lastBtn = headBtn;
            _line.backgroundColor = [UIColor colorWithString:@"#ed8929"];
            [self.view addSubview:_line];
        }
        
        [self.view addSubview:headBtn];
        
    }
    
    if ([[SendIFAPPDefault shareAppDefault].loginState intValue] == 0) {
        ALERT_WARN(@"没有登录!");
        return;
    }
    
    self.list = [[BeeUIScrollView alloc] initWithFrame:CGRectMake(0, 64+30, self.bounds.size.width, self.bounds.size.height-64-44-30)];
    [self.view addSubview: self.list];

    self.list.lineCount = 1;
    self.list.headerClass = [PullLoader class];
    self.list.headerShown = NO;
    self.list.footerClass = [FootLoader class];
    self.list.footerShown = NO;
    self.list.animationDuration = 0.25f;
    __weak CartBoard *car = self;
    
     self.list.whenReloading = ^{
        
         //配置总的个数
         int sumRow=0;
         for (int i = 0; i<car.historyData.count; i++) {
             
             sumRow++;//配置区头
             NSDictionary *dic = car.historyData[i];
             sumRow+=((NSArray*)dic[@"goods"]).count;
             sumRow++;//配置区尾
         }
         
         car.list.total = sumRow;
         int offset = 0;
         for (int j =0; j<car.historyData.count; j++) {
             
             //配置titleCell;
             NSDictionary *dic = [car.historyData safeObjectAtIndex:j];
             NSArray *goods = dic[@"goods"];
             BeeUIScrollItem *section = car.list.items[offset];
             
             section.size = CGSizeMake(car.list.bounds.size.width, 35);
             section.clazz = [SectionItemCell class];
             section.data = dic;
             
             offset++;
             
             for (int m =0; m<goods.count; m++) {
                 
                 BeeUIScrollItem *item = car.list.items[offset];
                 item.size = CGSizeMake(car.list.bounds.size.width, 120);
                 
                 if ([[goods safeObjectAtIndex:m] isKindOfClass:[CartM class]]) {
                     
                      item.clazz = [CartItemCell class];
                     
                 }else{
                     
                      item.clazz = [OrderCell class];
                 }
                 
                
                 
                 item.data = [goods safeObjectAtIndex:m];
                 offset++;
             }
             
             BeeUIScrollItem *footer = car.list.items[offset];
             footer.size = CGSizeMake(car.list.bounds.size.width, 30);
             footer.clazz = [CartFooterCell class];
             footer.data = dic;
             offset++;

         }
         
    };
    
    self.list.whenHeaderRefresh = ^{
        
        

        [car.ordm firstPage];
        
    };
    
    self.list.whenFooterRefresh = ^{
        

        [car.ordm nextPage];
        
    };
    

    [self createBottomView];
    
  
    NSArray *arr = [[_historyData firstObject] objectForKey:@"goods"];
    if (arr.count==0) {
        
        ALERT_WARN(@"购物车什么也没有，请到首页购买自己喜欢的产品");
    }

    
}
- (void)headBtnClick:(BeeUIButton*)btn
{
    
    [btn setTitleColor:[UIColor colorWithString:@"#ed8929"] forState:UIControlStateNormal];
    if (btn != _lastBtn) {
        [_lastBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    _lastBtn = btn;
    self.currentIndex = btn.tag;
    
    [UIView animateWithDuration:0.3 animations:^{
        
        _line.frame = CGRectMake(10+(btn.tag-100)*btn.size.width, CGRectGetMaxY(btn.frame)-3, btn.size.width-20, 3);
        
    } completion:^(BOOL finished) {
        
    }];
    
    if ([[SendIFAPPDefault shareAppDefault].loginState intValue] == 0) {
        
        [self presentMessageTips:@"请在个人中心登陆"];
        return;
    }
    
    if (btn.tag == 100) {
        
        NSDictionary *selectsD = [[NSUserDefaults standardUserDefaults] objectForKey:@"cart.selectgoods"];
        NSArray *goods = [CartM objectsFromArray:[selectsD allValues]];
        _historyData = @[@{@"goods":goods==nil?[NSArray new]:goods}];
        
        
        bottomV.hidden = NO;
        self.ordm.orderType = @"current";
        self.list.frame = CGRectMake(0, 64+30, self.bounds.size.width, self.bounds.size.height-64-30-44);
        self.list.headerShown = NO;
        self.list.footerShown = NO;

    }else if(btn.tag == 101){ //当前订单
        

        
//        CartM *cm1 = [CartM new];
//        cm1.orderType = @"1";
//        cm1.goodsNum = @"1";
//        CartM *cm2 = [CartM new];
//        cm2.orderType = @"1";
//        cm2.goodsNum = @"1";
//        CartM *cm3 = [CartM new];
//        cm3.orderType = @"1";
//        cm3.goodsNum = @"1";
//        
//        _historyData = @[@{@"goods":@[cm1,cm2,cm3]}];
        
        
        
        bottomV.hidden = YES;
        self.ordm.orderType = @"current";
        self.list.frame = CGRectMake(0, 64+30, self.bounds.size.width, self.bounds.size.height-64-30);
        self.list.headerShown = YES;
        self.list.footerShown = YES;
        
        self.list.headerLoading = YES;
        [self.ordm firstPage];
        
    }else if (btn.tag == 102){ //历史订单
    
    

        
        bottomV.hidden = YES;
        self.ordm.orderType = @"history";
        self.list.frame = CGRectMake(0, 64+30, self.bounds.size.width, self.bounds.size.height-64-30);
        self.list.headerShown = YES;
        self.list.footerShown = YES;
        
        self.list.headerLoading = YES;
        [self.ordm firstPage];
    }

}

- (void)createBottomView
{

    bottomV = [[UIView alloc] initWithFrame:CGRectMake(0, self.bounds.size.height-44, self.bounds.size.width, 44)];
    bottomV.clipsToBounds = NO;
    [self.view addSubview:bottomV];
    
    UIImageView *leftbg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width/2, 44)];
    leftbg.image = [UIImage imageNamed:@"cartbg"];
    [bottomV addSubview:leftbg];
    [bottomV sendSubviewToBack:leftbg];
    
    UIImageView *cartIcon = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"cartIcon"]];
    cartIcon.frame = CGRectMake(10, -20, 60, 60);
    cartIcon.clipsToBounds = NO;
    [bottomV addSubview:cartIcon];
    
    numLab = [[UILabel alloc] initWithFrame:CGRectMake(45, 2, 20, 20)];
    numLab.backgroundColor = RGB(245, 34, 71);
    NSDictionary *dic = _historyData[0];
    NSArray *cars = dic[@"goods"];
    
    int nums=0;
    float price=0.00;
    
    for (CartM *cm in cars) {
        NSLog(@"goods nums ====%@",cm.goods.price);
        nums+=[cm.goodsNum integerValue];
        price+= [cm.goodsNum integerValue]*[cm.goods.price floatValue];
    }
    numLab.text = [NSString stringWithFormat:@"%d",nums];
    numLab.textAlignment = NSTextAlignmentCenter;
    numLab.textColor = [UIColor whiteColor];
    numLab.font = [UIFont systemFontOfSize:14];
    numLab.layer.cornerRadius = 10;
    numLab.layer.masksToBounds = YES;
    [cartIcon addSubview:numLab];
    
    priceLab = [[UILabel alloc] initWithFrame:CGRectMake(CGRectGetMaxX(cartIcon.frame)+5, 10, 100, 20)];
    
    priceLab.text = [NSString stringWithFormat:@"共%.2f元",price];
    priceLab.font = [UIFont systemFontOfSize:16];
    [bottomV addSubview:priceLab];
    

    UIButton *payBtn = [[UIButton alloc] initWithFrame:CGRectMake(CGRectGetMaxX(leftbg.frame), 0, self.bounds.size.width/2, 44)];
    [payBtn setTitle:@"立即下单" forState:UIControlStateNormal];
    [payBtn addTarget:self action:@selector(payBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [payBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    payBtn.titleLabel.font = [UIFont systemFontOfSize:18];
    payBtn.backgroundColor = RGB(245, 34, 71);
    [bottomV addSubview:payBtn];

}
- (void)payBtnClick:(UIButton*)btn
{

    if ([[SendIFAPPDefault shareAppDefault].loginState intValue]==0) {
        
        [self presentFailureTips:@"请先登录!"];
        return;
    }
    NSArray *goods = [[_historyData firstObject] objectForKey:@"goods"];
    
    if (goods.count == 0) {
        
         [self presentMessageTips:@"购物车空的，请先选择产品后再下单"];
        return;       
        
    }

    SelectAddressCell *cell = [[SelectAddressCell alloc] initWithFrame:CGRectMake(10, 80, self.size.width-20, self.view.bounds.size.height-80-75)];
    cell.RELAYOUT();
    [self presentModalView:cell animated:YES];

}
ON_SIGNAL3(BeeUIBoard, MODALVIEW_WILL_HIDE, signal)
{

    _lastAddressCell = nil;

}
ON_SIGNAL3(CartBoard, back, signal)
{

    BeeUIButton *btn = (BeeUIButton*)signal.sourceView;
    [btn addTarget:self.navigationController.parentViewController action:@selector(revealToggle:) forControlEvents:UIControlEventTouchUpInside];

}
#pragma mark 选择地址确定
ON_SIGNAL3(SelectAddressCell, suremod, signal)
{
    //确定选择地址
    if (!_lastAddressCell) {
        
        [self presentMessageTips:@"请选择收货地址"];
        return;
    }
    
    
    //开始下单
    
    NSDictionary *dic = _historyData[0];
    NSArray *cars = dic[@"goods"];
    CartM *cm = [cars firstObject];
    float price = 0.00;
    NSMutableString *productsid = [[NSMutableString alloc] initWithCapacity:0];
    NSMutableString *numids = [[NSMutableString alloc] initWithCapacity:0];
    
    NSMutableArray *carss = [[NSMutableArray alloc] initWithCapacity:0];
    
    for (CartM *cmrr in cars) {
        
        if ([cmrr.goodsNum intValue]>0) {
            
            [carss addObject:cmrr];
        }
    
    }

    _noZeroArr = carss;
    for (CartM *cmm in carss) {
        
  
        
        _allGoodsNum+=[cmm.goodsNum intValue];
        price+= [cmm.goodsNum integerValue]*[cmm.goods.price floatValue];
        NSString *gid = [NSString stringWithFormat:@"%@,",cmm.goods.id];
        [productsid appendString:gid];
        
        NSString *numid = [NSString stringWithFormat:@"%d,",[cmm.goodsNum intValue]];
        [numids appendString:numid];
        
        NSLog(@"name===%@ gid=%@ num===%@",cmm.goods.title,cmm.goods.id,cmm.goodsNum);
    }
    NSString *gids = [productsid substringToIndex:productsid.length-1];
    NSString *relNumids = [numids substringToIndex:numids.length-1];
    _seleGids = gids;
    

    
    self.MSG(HttpAPI.order_checkout).INPUT(@"body",@{@"token":[SendIFAPPDefault shareAppDefault].userToken,@"shopId":[SendIFAPPDefault shareAppDefault].selectedGoodsShopID,@"productId":_seleGids});
    
    

    


}

ON_MESSAGE3(HttpAPI, order_add, msg)
{

    if (msg.sending) {
        
        [self presentLoadingTips:@"正在创建订单"];
        
    }else{
        
        [self dismissTips];
        
        if (msg.succeed) {
            
            
            
            Status *sta = msg.GET_OUTPUT(@"status");
            if ([sta.code intValue] != 10000) {
                
                [self presentFailureTips:sta.message];
                return;
            }
            
            //下单成功后,显示支付界面并获取订单信息
            
            [[NSUserDefaults standardUserDefaults] removeObjectForKey:@"cart.selectgoods"];
            _orderId = msg.GET_OUTPUT(@"orderId");
            
            
            HomeBoard *home = [[HomeBoard alloc] init];
            home.homeType = @"pay";
            home.orderId = _orderId;
            NSDictionary *dic = _historyData[0];
            //NSArray *cars = dic[@"goods"];
            home.goodsArr = _noZeroArr;
            home.add = _lastAddressCell.data;
            
            NSArray *pays = msg.GET_OUTPUT(@"pays");
            NSString *fee = msg.GET_OUTPUT(@"fee");
            home.pays = pays;
            home.fee = fee;
            [self dismissModalViewAnimated:YES];
            [self.stack pushBoard:home animated:YES];

            
        }else{
            
            [self presentFailureTips:@"网络错误"];
            
        }
        
    }

}
ON_MESSAGE3(HttpAPI, order_checkout, msg)
{

    if (msg.sending) {
        
        [self presentLoadingTips:@"正在获取订单信息"];
        
    }else{
        
        [self dismissTips];
        
        if (msg.succeed) {
            
            
            
            Status *sta = msg.GET_OUTPUT(@"status");
            if ([sta.code intValue] != 10000) {
                
                [self presentFailureTips:sta.message];
                return;
            }
            
            NSDictionary *dic = _historyData[0];
            NSArray *cars = dic[@"goods"];
            CartM *cm = [cars firstObject];
            float price = 0.00;
            NSMutableString *productsid = [[NSMutableString alloc] initWithCapacity:0];
            NSMutableString *numids = [[NSMutableString alloc] initWithCapacity:0];
            
            NSMutableArray *carss = [[NSMutableArray alloc] initWithCapacity:0];
            
            for (CartM *cmrr in cars) {
                
                if ([cmrr.goodsNum intValue]>0) {
                    
                    [carss addObject:cmrr];
                }
                
            }
            _noZeroArr = carss;
            for (CartM *cmm in carss) {
                

                _allGoodsNum+=[cmm.goodsNum intValue];
                price+= [cmm.goodsNum integerValue]*[cmm.goods.price floatValue];
                NSString *gid = [NSString stringWithFormat:@"%@,",cmm.goods.id];
                [productsid appendString:gid];
                
                NSString *numid = [NSString stringWithFormat:@"%d,",[cmm.goodsNum intValue]];
                [numids appendString:numid];
                
                NSLog(@"商品名===%@ 商品id=%@ 商品个数===%@",cmm.goods.title,cmm.goods.id,cmm.goodsNum);
            }
            NSString *gids = [productsid substringToIndex:productsid.length-1];
            NSString *relNumids = [numids substringToIndex:numids.length-1];
            
            
            Address *addr = _lastAddressCell.data;
            
            NSDictionary *orderD = @{@"token":[SendIFAPPDefault shareAppDefault].userToken,
                                     @"shopId":[SendIFAPPDefault shareAppDefault].selectedGoodsShopID,//暂时写死
                                     @"userName":@"",
                                     @"goods_sumPrice":@"", //商品总额
                                     @"order_sumPrice":[NSString stringWithFormat:@"%.2f",price], //订单总额
                                     @"address_name":addr.name,
                                     @"mobile":addr.mobile,
                                     @"address":addr.address,
                                     @"supportmetho":@"1",   //支付方式
                                     @"freeprice":@"0.00",      //快递费用
                                     @"product_str":gids,    //产品，多个用逗号拼接
                                     @"quantity":relNumids,
                                     @"expected_time":@"",  //配送时间
                                     @"note":@"",           //备注
                                     @"orderType":@"1"       //1．外卖  2. 生鲜配送。3 预售
                                     };
            
            self.MSG(HttpAPI.order_add).INPUT(@"body",orderD);
            
            

            
            
        }else{
            
            [self presentFailureTips:@"网络错误"];
            
        }
        
    }
    


}

ON_SIGNAL3(SelectAddressCell, add, signal)
{
    
    [self dismissModalViewAnimated:YES];
    
    addAddressCell *cell = [[addAddressCell alloc] initWithFrame:CGRectMake(10, 120, self.size.width-20, self.view.bounds.size.height-120-75)];
    cell.RELAYOUT();
    [self presentModalView:cell animated:YES];
}
ON_SIGNAL3(addAddressCell, sureadd, signal)
{

    addAddressCell *cell = (addAddressCell*)signal.sourceCell;
    
    NSString *name = $(cell).FIND(@"nametf").text;
    NSString *phone = $(cell).FIND(@"phonetf").text;
    NSString *address = $(cell).FIND(@"addresstf").text;
    
    if (![phone isMobilephone]) {
        [self presentFailureTips:@"请输入有效的手机号"];
        return;
    }
    if (name.length==0||phone.length==0||address.length==0) {
        
        [self presentFailureTips:@"请完善地址信息"];
        return;
    }
    
    NSDictionary *dic = @{@"token":[SendIFAPPDefault shareAppDefault].userToken,@"name":name,@"mobile":phone,@"address":address,@"remark":@""};
    self.MSG(HttpAPI.address_add).INPUT(@"body",dic);

}
ON_SIGNAL3(addAddressCell, addnewaddress, signal)
{

    [self dismissModalViewAnimated:YES];
    addAddressCell *cell = [[addAddressCell alloc] initWithFrame:CGRectMake(10, 120, self.size.width-20, self.view.bounds.size.height-120-75)];
    cell.RELAYOUT();
    [self presentModalView:cell animated:YES];
}
ON_SIGNAL3(SelectAddressItemCell, mask, signal)
{
    
    SelectAddressItemCell *cell = (SelectAddressItemCell *)signal.sourceCell;
    BeeUIImageView *img = (BeeUIImageView*)$(cell).FIND(@"select").view;
    img.image = [UIImage imageFromString:@"checked_1"];
    
    if (cell != _lastAddressCell) {
        
        BeeUIImageView *img = (BeeUIImageView*)$(_lastAddressCell).FIND(@"select").view;
        img.image = [UIImage imageFromString:@"unchecked_1"];
        
    }
    _lastAddressCell = cell;

}
ON_MESSAGE3(HttpAPI, address_add, msg)
{

    if (msg.sending) {
       
         [self presentLoadingTips:@"添加地址中"];
        
    }else{
    
        [self dismissTips];
        
        if (msg.succeed) {
            
            Status *sta = msg.GET_OUTPUT(@"status");
            if ([sta.code intValue] != 10000) {
                
                [self presentFailureTips:sta.message];
                
            }else{
            
                [self dismissModalViewAnimated:YES];
            
            }
            
        }else if (msg.failed){
            
            [self presentFailureTips:@"网络错误"];
        }
    
    }

}

ON_SIGNAL2(OrderM, signal)
{
    
    if ([signal is:OrderM.RELOADING]) {
        
        self.list.footerLoading = YES;
        
        
    }else if ([signal is:OrderM.RELOADED])
    {
        [self dismissTips];
        
        [self.list setHeaderLoading:NO];
        [self.list setFooterLoading:NO];

        
        NSMutableArray *datas = [[NSMutableArray alloc] initWithCapacity:0];
        
        for (Order *ord in self.ordm.ordersArray) {
            
  
            
            NSDictionary *ordD = @{@"time":ord.add_time,@"goods":ord.products?:[NSArray new],@"order":ord};
            [datas addObject:ordD];
            
        }
        
        _historyData = datas;
        
        [self.list asyncReloadData];
    }
}

#pragma mark - 修改数量
ON_SIGNAL3(CartItemCell, bottomplus, signal)
{

    CartItemCell *cell = (CartItemCell *)signal.sourceCell;
    BeeUILabel *lab = (BeeUILabel*)$(cell).FIND(@"numvalue").view;
    int _num = [lab.text intValue];
    CartM *cm = cell.data;
    
    _num++;
    _allGoodsNum = 0;
    $(cell).FIND(@"numvalue").DATA([NSString stringWithFormat:@"%d",_num]);
    cm.goodsNum = [NSString stringWithFormat:@"%d",_num];
    NSDictionary *dic = _historyData[0];
    NSArray *cars = dic[@"goods"];
    float price = 0.00;
    for (CartM *cmm in cars) {
        
        _allGoodsNum+=[cmm.goodsNum intValue];
        price += [cmm.goodsNum integerValue]*[cmm.goods.price floatValue];
    }
    numLab.text = [NSString stringWithFormat:@"%d",_allGoodsNum];
    priceLab.text = [NSString stringWithFormat:@"共%.2f元",price];
    
    
}
ON_SIGNAL3(CartItemCell, bottomminus, signal)
{
    CartItemCell *cell = (CartItemCell *)signal.sourceCell;
    
    CartM *cm = cell.data;
    BeeUILabel *lab = (BeeUILabel*)$(cell).FIND(@"numvalue").view;
    int _num = [lab.text intValue];
    
    _num--;
    _allGoodsNum = 0;
    if (_num < 0) {
        
        _num = 0;
    }
    $(cell).FIND(@"numvalue").DATA([NSString stringWithFormat:@"%d",_num]);
    cm.goodsNum = [NSString stringWithFormat:@"%d",_num];
    
    NSDictionary *dic = _historyData[0];
    NSArray *cars = dic[@"goods"];
    float price = 0.00;
    
    for (CartM *cmm in cars) {
        
        _allGoodsNum+=[cmm.goodsNum intValue];
        price+= [cmm.goodsNum integerValue]*[cmm.goods.price floatValue];
    }
    numLab.text = [NSString stringWithFormat:@"%d",_allGoodsNum];
    priceLab.text = [NSString stringWithFormat:@"共%.2f元",price];
    
}
#pragma mark - 订单详情
ON_SIGNAL3(CartFooterCell, mask, signal)
{




    
    NSDictionary *dic = signal.sourceCell.data;
    Order *om = dic[@"order"];
    if ([om.status intValue] != 1) {
        
        return;
    }
    if (!om.orderId) {
        
        return;
    }
    self.MSG(HttpAPI.order_detail).INPUT(@"body",@{@"token":[SendIFAPPDefault shareAppDefault].userToken,@"orderId":om.orderId});
    
}
ON_MESSAGE3(HttpAPI, order_detail, msg)
{

    if (msg.sending) {
        
        [self presentMessageTips:@"数据获取中"];
        
    }else{
    
        [self dismissTips];
        if (msg.succeed) {
            
            Status *sta = msg.GET_OUTPUT(@"status");
            if ([sta.code intValue] != 10000) {
                
                [self presentMessageTips:sta.message];
                return;
            }
            //
            Order *om = msg.GET_OUTPUT(@"order");
            if ([om.status intValue]==1) { //未付款
                
                HomeBoard *homeb = [[HomeBoard alloc] init];
                homeb.homeType = @"pay";
                NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:0];
                for (OrderGoods *gd in om.products) {
                    
                    CartM *cm = [CartM new];
                    Goods *goo = [Goods new];
                    
                    goo.title = gd.title;
                    cm.goodsNum = gd.quantity;
                    goo.price = gd.price;
                    goo.pic = gd.img;
                    cm.goods = goo;
                    [arr addObject:cm];
                }
                Address *add = [Address new];
                add.name = om.address_name;
                add.address = om.address;
                add.mobile = om.mobile;
                homeb.add = add;
                
                homeb.goodsArr = arr;
                homeb.orderId = om.orderId;
                [self.stack pushBoard:homeb animated:YES];
            }
            
        }else{
        
            [self presentFailureTips:@"网络错误"];
        }
    
    }

}
@end
